#!/usr/bin/env python
# encoding: utf-8

import codecs
import json
import re
import urllib
import urllib2

from urllib import urlopen

class UnknownNameError(ValueError):
	""" Invalid category or unit name. """

def main(env):

	def extractCategory(suffix):
		if suffix:
			for category in env["static"]["cwConvert_categories"]:
				if suffix.startswith(category):
					return (category,suffix[len(category):])
		category = env["prefs"]["cwConvert_defaultCategory"]
		if category in env["static"]["cwConvert_categories"]:
			return (category,suffix)
		raise UnknownNameError,(env["static"]["cwConvert_badDefaultCategory"] % category)
	
	def validateUnitName(key,unitName):
		if unitName:
			if unitName not in unitNames:
				raise UnknownNameError,(env["static"]["cwConvert_bad%s" % key] % (unitName,category))
		else:
			unitName = env["prefs"]["cwConvert_default%s%s" % (key,internationalCategory.title())]
			if unitName not in unitNames:
				raise UnknownNameError,(env["static"]["cwConvert_badDefault%s" % key] % (unitName,category))
		return unitName

        def updatecurrencies():
                    urllib.urlretrieve('https://raw.github.com/currencybot/open-exchange-rates/master/latest.json', 'currencyRates.json')
                
        
	try:
                updatecurrencies()
		(category,target) = extractCategory(env["meta"]["richSuffix"].lower())
		internationalCategory = env["static"]["cwConvert_categories"][category]
		unitFileName = "%s_%sUnitNames.json" % (env["constants"]["language"],internationalCategory)
		unitNames = json.loads(codecs.open(unitFileName,"r","utf8").read())
		unitNames.update(dict((a,a) for a in unitNames.itervalues())) # add standard abbreviations as valid unit names
		target = validateUnitName("Target",target)
		rateFileName = "%sRates.json" % internationalCategory
		rates = json.loads(codecs.open(rateFileName,"r","utf8").read())
		match = re.match(r".*\b(-?[0-9]+(?:[,.][0-9]+)?(?:[eE][+-]?[0-9]+)?)\s*(.*)",env["context"]["selection"])
		if match is None:
			return [("messageBox","%s: conversions for 1 %s." % (category,target))]
		(number,base) = match.groups()
		base = validateUnitName("Base",base.strip())
		result = float(number) / rates["rates"][unitNames[base]] * rates["rates"][unitNames[target]]
		return [("messageBox","%s: %s %s = %s %s." % (category,number,base,result,target))]
	except UnknownNameError as e:
		return [("messageBox",e.args[0])]
        return [("append", "Mise a jour termine")]